package com.ovopark.firecar.okhttp;


import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * uuid过期拦截器,自动重新登录
 * Created by lijian on 2017/02/28.
 */

public class TokenInterceptor implements Interceptor {
    private static final String TAG = "TokenInterceptor";

    private static final Charset UTF8 = Charset.forName("UTF-8");

    private static final int MAX_TOKEN_RETRY_COUNT = 5;
    /**
     * token失效的次数. 如果超过5个接口继续报错，则刷新token.
     */
    private int mTokenFailCount = 0;



    public TokenInterceptor() {
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        // try the request
        Response originalResponse = chain.proceed(request);
        ResponseBody responseBody = originalResponse.body();
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.buffer();
        Charset charset = UTF8;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(UTF8);
        }

//        String bodyString = buffer.clone().readString(charset);
//        if (bodyString.contains("\"result\":\"INVALID_TOKEN\"")||//无效token
//                bodyString.contains("\"result\":\"TOKEN_EXPIRED\"")||
//                bodyString.contains("\"message\":\"TOKEN_EXPIRATION\"")||//uuid过期
//                bodyString.contains("\"code\":\"9990001\"")
//        ) {
//            KLog.d(TAG,bodyString);
//            mTokenFailCount++;
//            if(mTokenFailCount >= MAX_TOKEN_RETRY_COUNT){
//                mTokenFailCount = 0;
//                if(null != LoginUtils.getCachedUser()&&LoginUtils.getCachedUser().isTokenRefreshing()){
//                    //重置标志位，触发新一轮的刷新token.
//                    LoginUtils.getCachedUser().setTokenRefreshing(false);
//                }
//            }
//            //通知HomeActivity刷新token.
//            EventBus.getDefault().post(new UserToken(true));
//        }
        // otherwise just pass the original response on
        return originalResponse;
    }
}